<script setup>
import { ref, onMounted, computed } from 'vue'
import { UserProfileApi } from "@/api/new/userProfleApi.js";
import UserUtil from "@/utils/User/User.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
// 导入图标组件
import { Delete, Share, ArrowDown } from '@element-plus/icons-vue';
import { ArticleApi } from "@/api/articleApi";

const router = useRouter();
const activeIndex = ref('1') // 默认1
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(5)
const totalArticles = ref(0)
const loading = ref(false)

// 文章列表
const articles = ref([])
const userId = computed(() => UserUtil.getUserId())

// 文章状态映射
const statusMap = {
  'published': '已发布',
  'draft': '草稿',
  'pendingReview': '待审核',
  'deleted': '已删除'
}

// 文章状态标签样式
const statusTagType = (status) => {
  switch(status) {
    case 'published': return 'success';
    case 'draft': return 'warning';
    case 'pendingReview': return 'info';
    case 'deleted': return 'danger';
    default: return 'info';
  }
}

onMounted(() => {
  fetchArticles();
})

// 获取文章列表
const fetchArticles = async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    loading.value = true;
    const res = await UserProfileApi.viewPublishedArticles(
      userId.value, 
      currentPage.value, 
      pageSize.value
    );
    console.log('稿件管理页面',res);
    
    if (res && Array.isArray(res)) {
      // 根据当前选中的标签过滤文章
      if (activeTab.value === 'all') {
        articles.value = res;
      } else {
        articles.value = res.filter(article => article.status === activeTab.value);
      }
      totalArticles.value = articles.value.length;
    } else {
      articles.value = [];
      totalArticles.value = 0;
    }
  } catch (error) {
    console.error('获取文章失败:', error);
    ElMessage.error('获取文章列表失败');
  } finally {
    loading.value = false;
  }
}

// 编辑文章
const editArticle = (article) => {
  // 跳转到编辑页面
  router.push({
    name: 'platform.editArticle',
    params: { id: article.articleID }
  });
}

// 查看文章数据
const viewArticleStats = (article) => {
  router.push({
    name: 'ArticleStats',
    params: { id: article.articleID }
  });
}

// 删除文章
const deleteArticle = async (article) => {
  ElMessageBox.confirm(
    '确定要删除这篇文章吗？此操作不可逆',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      loading.value = true;
      // 使用ArticleApi删除文章
      await ArticleApi.deleteArticle(article.articleID);
      ElMessage.success('删除成功');
      // 重新获取文章列表
      fetchArticles();
    } catch (error) {
      console.error('删除文章失败:', error);
      ElMessage.error(`删除失败: ${error.message || '未知错误'}`);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除');
  });
}

// 分享文章
const shareArticle = (article) => {
  // 复制文章链接到剪贴板
  const url = `${window.location.origin}/article/${article.articleID}`;
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('文章链接已复制到剪贴板');
  }).catch(err => {
    console.error('复制失败:', err);
    ElMessage.error('复制链接失败');
  });
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchArticles();
}

// 处理菜单选择
const handleSelect = (key) => {
  activeIndex.value = key;
  // 根据选择的菜单项筛选文章
  if (key === '1') {
    activeTab.value = 'all';
  } else if (key === '2') {
    activeTab.value = 'published';
  } else if (key === '3') {
    activeTab.value = 'draft';
  }
  currentPage.value = 1;
  fetchArticles();
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 获取文章摘要
const getArticleSummary = (content) => {
  if (!content) return '无内容';
  return content.length > 100 ? content.substring(0, 100) + '...' : content;
}
</script>

<template>
  <div class="upload-manage-view">
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="handleSelect"
    >
      <el-menu-item index="1">全部稿件</el-menu-item>
      <el-menu-item index="2">已发布文章</el-menu-item>
      <el-menu-item index="3">草稿箱</el-menu-item>
    </el-menu>
    
    <div class="article-list-container">
      <el-empty v-if="articles.length === 0" description="暂无文章" />
      
      <el-skeleton v-if="loading" :rows="5" animated />
      
      <div v-else class="article-list">
        <div v-for="article in articles" :key="article.articleID" class="article-item">
          <div class="article-info">
            <div class="article-header">
              <h3 class="article-title">{{ article.title }}</h3>
              <el-tag :type="statusTagType(article.status)" size="small">
                {{ statusMap[article.status] || article.status }}
              </el-tag>
            </div>
            <p class="article-summary">{{ getArticleSummary(article.content) }}</p>
            <div class="article-stats">
              <span>创建时间: {{ formatDate(article.creationTime) }}</span>
              <!-- <span>点赞: {{ article.likeCount || 0 }}</span> -->
              <span>收藏: {{ article.favoriteCount || 0 }}</span>
              <span>评论: {{ article.commentCount || 0 }}</span>
            </div>
          </div>
          <div class="article-actions">
            <el-button class="article-actions-editBtn" type="primary" plain @click="editArticle(article)">编辑</el-button>
            <el-button type="danger" plain @click="deleteArticle(article)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="totalArticles"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.upload-manage-view {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .el-menu-demo {
    border-radius: 8px 8px 0 0;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 0;
    
    .el-menu-item {
      font-size: 16px;
      font-weight: 500;
      height: 60px;
      line-height: 60px;
      
      &.is-active {
        font-weight: 600;
      }
    }
  }
  
  .article-list-container {
    background-color: white;
    border-radius: 0 0 8px 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    min-height: 400px;
    
    .article-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    
    .article-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      border-radius: 8px;
      border: 1px solid #ebeef5;
      transition: all 0.3s;
      
      &:hover {
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }
      
      .article-info {
        flex: 1;
        
        .article-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          
          .article-title {
            margin: 0;
            margin-right: 10px;
            font-size: 18px;
            font-weight: 600;
            color: #303133;
          }
        }
        
        .article-summary {
          margin: 0 0 10px;
          color: #606266;
          font-size: 14px;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        
        .article-stats {
          display: flex;
          flex-wrap: wrap;
          gap: 15px;
          
          span {
            color: #909399;
            font-size: 13px;
          }
        }
      }
      
      .article-actions {
        display: flex;
        gap: 10px;

        .article-actions-editBtn{
          color: #ffffff;
        }
        
        .el-button {
          padding: 8px 15px;
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
